/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import dao.*;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JDialog;
import javax.swing.table.DefaultTableModel;
import model.*;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author JONATAS
 */
public class ProjetoDialog extends javax.swing.JDialog {

    /**
     * Creates new form ClasseDialog
     */
    public ProjetoDialog(java.awt.Frame parent, boolean modal) {
        
        super(parent, modal);
        initComponents();
        this.requestFocus();
        this.tbValor1.requestFocus();
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel5 = new javax.swing.JPanel();
        cmbCampo = new javax.swing.JComboBox();
        cmbCondicao = new javax.swing.JComboBox();
        btnBuscar = new javax.swing.JButton();
        tbValor2 = new javax.swing.JTextField();
        lbE = new javax.swing.JLabel();
        tbValor1 = new javax.swing.JTextField();
        chkAbertos = new javax.swing.JCheckBox();
        chkEmConstrucao = new javax.swing.JCheckBox();
        chkConcluidos = new javax.swing.JCheckBox();
        chkExcluidos = new javax.swing.JCheckBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Consulta de Projetos");
        setAutoRequestFocus(false);
        setModalExclusionType(null);
        setModalityType(java.awt.Dialog.ModalityType.DOCUMENT_MODAL);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Cliente", "Descrição", "Data Prev.Início", "Data Prev. Fim", "Endereço Constr.", "Status"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jPanel5.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        cmbCampo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nome Cliente", "CPF/CNPJ", "Codigo projeto", "Data Inicio Prevista", "Data Fim Prevista", "Data Fim" }));

        cmbCondicao.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Contém", "Igual", "Entre", "Maior que", "Menor que" }));
        cmbCondicao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbCondicaoActionPerformed(evt);
            }
        });

        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        tbValor2.setEnabled(false);

        lbE.setText("e");

        chkAbertos.setSelected(true);
        chkAbertos.setText("Abertos");

        chkEmConstrucao.setSelected(true);
        chkEmConstrucao.setText("Em construção");
        chkEmConstrucao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkEmConstrucaoActionPerformed(evt);
            }
        });

        chkConcluidos.setSelected(true);
        chkConcluidos.setText("Concluídos");

        chkExcluidos.setText("Excluídos");
        chkExcluidos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkExcluidosActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(chkEmConstrucao)
                            .addComponent(chkAbertos))
                        .addGap(13, 13, 13)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(chkConcluidos)
                            .addComponent(chkExcluidos))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnBuscar))
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(cmbCampo, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbCondicao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tbValor1, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbE, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tbValor2)))
                .addGap(12, 12, 12))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbCampo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmbCondicao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tbValor2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbE)
                    .addComponent(tbValor1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnBuscar)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(chkAbertos)
                            .addComponent(chkConcluidos))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(chkEmConstrucao)
                            .addComponent(chkExcluidos))))
                .addContainerGap())
        );

        jButton1.setText("Selecionar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Imprimir ");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 725, Short.MAX_VALUE)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 442, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-767)/2, (screenSize.height-655)/2, 767, 655);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened

        buscarProjetos();

    }//GEN-LAST:event_formWindowOpened

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        if (evt.getClickCount() == 2) {
            selecionar();
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void selecionar() {
        int linha = jTable1.getSelectedRow();
        String codigo = "" + jTable1.getValueAt(linha, 0);

        this.projeto = new Projeto();
        this.projeto.setPro_id(Integer.parseInt(codigo));

        projeto = new ProjetoDAO().findById(projeto.getPro_id());

        this.setVisible(false);
    }

    private void cmbCondicaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbCondicaoActionPerformed
        if (cmbCondicao.getSelectedIndex() == 2) {
            tbValor2.setEnabled(true);
            lbE.setEnabled(true);
        } else {
            tbValor2.setEnabled(false);
            lbE.setEnabled(false);
        }
    }//GEN-LAST:event_cmbCondicaoActionPerformed

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        buscarProjetos();
    }

    private void buscarProjetos() {
       
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        String campo;
        String condicao;
        String situacao;
        String valor1;
        String valor2;
        switch (cmbCampo.getSelectedIndex()) { //Nome Cliente, CPF/CNPJ, Codigo projeto, Data Inicio Prevista, Data Fim Prevista, Data Fim
            case 0:
                campo = " upper(cliente.nomeCompleto) ";
                break;
            case 1:
                campo = " cliente.cliente_id.cpf_cnpj ";
                break;
            case 2:
                campo = " pro_id ";
                break;
            case 3:
                campo = " pro_dataInicioPrevista ";
                break;
            case 4:
                campo = " pro_dataFimPrevista ";
                break;
            case 5:
                campo = " pro_dataEncerra ";
                break;
            default:
                campo = " upper(nomeCompleto) ";
                break;
        }
        switch (cmbCondicao.getSelectedIndex()) {
            case 0:
                condicao = " like ";
                break;
            case 1:
                condicao = " = ";
                break;
            case 2:
                condicao = " between ";
                break;
            case 3:
                condicao = " >= ";
                break;
            case 4:
                condicao = " <= ";
                break;
            default:
                condicao = " like ";
                break;
        }
        situacao = " and pro_status in (";
        int flag = 0; // indica se a situacao ja foi usada
        if (chkAbertos.isSelected()) {
            situacao = situacao + " 0 ";
            flag = 1;
        }
        if (chkEmConstrucao.isSelected()) {
            if (flag != 1) {
                situacao = situacao + " 1 ";
                flag = 1;
            } else {
                situacao = situacao + ", 1 ";
            }
        }
        if (chkConcluidos.isSelected()) {
            if (flag != 1) {
                situacao = situacao + " 2 ";
                flag = 1;
            } else {
                situacao = situacao + ", 2 ";
            }
        }
        if (chkExcluidos.isSelected()) {
            if (flag != 1) {
                situacao = situacao + " -1 ";
                flag = 1;
            } else {
                situacao = situacao + ", -1 ";
            }
        }
        situacao = situacao + " ) ";
        System.out.println(" situacoes -> " + situacao);

        valor1 = tbValor1.getText().toUpperCase();
        if (condicao == " like ") {
            valor1 = "%" + valor1 + "%";
        }
        valor1 = "'" + valor1 + "'";
        SQL = " " + campo + condicao + valor1;

        if (condicao == " between ") {
            valor2 = " and " + "'" + tbValor2.getText().toUpperCase() + "'";
            SQL = SQL + valor2;
        }
        SQL = SQL + situacao + " order by pro_id ";

        System.out.println("SQL -> " + SQL);

        List<Projeto> lista = prodao.findCustomizado(SQL);

        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        modelo.setNumRows(0);
        int i = 0;
        for (Projeto m : lista) {
            situacao = "Erro";

            switch (m.getPro_status()) {
                case -1:
                    situacao = "Excluído";
                    break;
                case 0:
                    situacao = "Aberto";
                    break;
                case 1:
                    situacao = "Em construção";
                    break;
                case 2:
                    situacao = "Concluído";
                    break;
            }
            modelo.addRow(new String[]{"" + m.getPro_id(), "" + m.getCliente().getNomeCompleto(), m.getPro_descricao(), "" + sdf.format(m.getPro_dataInicioPrevista()),  sdf.format(m.getPro_dataFimPrevista()), "" + m.getPro_logradouroInst() + ", " + m.getPro_bairroInst() + ", " + m.getPro_cidadeInst(), situacao});            
        }
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void chkEmConstrucaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkEmConstrucaoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_chkEmConstrucaoActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        selecionar();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        
        System.out.println("SQL para imprimir relat'orio -> where -> "+SQL);   
        
        JRBeanCollectionDataSource jrs = new JRBeanCollectionDataSource(prodao.findCustomizado(SQL));
        // Parametros
        Map parametros = new HashMap();
        parametros.put("busca", "valor filtrado");

        try {
            // Carrega o relatório para ser executado
            JasperPrint jpr = JasperFillManager.fillReport("reports/relatorio_projetos.jasper", parametros, jrs);
            // Mostra o relatório - faz o show
            JasperViewer.viewReport(jpr, false);
        } catch (JRException ex) {
            Logger.getLogger(ProjetoFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void chkExcluidosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkExcluidosActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_chkExcluidosActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ProjetoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ProjetoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ProjetoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ProjetoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ProjetoDialog dialog = new ProjetoDialog(new javax.swing.JFrame(), false);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }    
    private String SQL;
    private Projeto projeto = new Projeto();
    private ProjetoDAO prodao = new ProjetoDAO();
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JCheckBox chkAbertos;
    private javax.swing.JCheckBox chkConcluidos;
    private javax.swing.JCheckBox chkEmConstrucao;
    private javax.swing.JCheckBox chkExcluidos;
    private javax.swing.JComboBox cmbCampo;
    private javax.swing.JComboBox cmbCondicao;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lbE;
    private javax.swing.JTextField tbValor1;
    private javax.swing.JTextField tbValor2;
    // End of variables declaration//GEN-END:variables

    public Projeto getProjeto() {
        return projeto;
    }

    public void setMaterialComponente(Projeto projeto) {
        this.projeto = projeto;
    }
}
